import { Cell, CellProps } from '../../doc/cell';

export function text(cell: Cell, attrs: CellProps) {
	if (!attrs.readonly) {
		cell.attr('contenteditable', 'plaintext-only');
	}
	cell.text(cell.getValue() ?? '');
	cell.on('keydown', (evt) => {
		if (evt.key === 'Enter' && attrs.multiline !== true) {
			evt.preventDefault();
		}
	});
	cell.on('input', () => {
		let txt = cell.text();
		if (attrs.multiline !== true) {
			if (/[\r\n]/.test(txt)) {
				txt = txt.replace(/[\r\n]/g, ' ');
				cell.text(txt);
				cell.setValue(txt);
			} else {
				cell.setValue(txt);
			}
		} else {
			cell.setValue(txt);
		}
		cell.emitChange();
	});
}
